package com.jh.util;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.util.Properties;

/**
 * yml文件获取配置工具
 *
 * @ClassName: YmlUtils
 * @Description: yml文件获取配置工具
 */
public class YmlUtils {

    /**
     * 获取yml配置文件4种方式
     * 方式1：属性注解@Value
     * 方式2：类注解@ConfigurationProperties("前缀")
     * 方式3：@Environment
     * 方式4：该工具类解析文件
     */

    /** 文件名称 */
    private static String PROPERTY_NAME = "config/application.yml";

    /**
     * 根据key获取yml配置文件
     * @author guoy
     * @param * @param key
     * @return java.lang.Object
     * @date 2020/6/12
     */
    public static Object getCommonYml(Object key){
        Resource resource = new ClassPathResource(PROPERTY_NAME);
        Properties properties = null;
        try {
            YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();
            yamlFactory.setResources(resource);
            properties =  yamlFactory.getObject();
            //获取激活配置文件
            String active = properties.getProperty("spring.profiles.active");
            resource = new ClassPathResource("config/application-"+active+".yml");
            yamlFactory = new YamlPropertiesFactoryBean();
            yamlFactory.setResources(resource);
            properties =  yamlFactory.getObject();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return properties.get(key);
    }

}
